package com.phynos.web.manager.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.phynos.lib.common.captcha.CaptchaUtil;
import com.phynos.web.manager.json.JsonResult;
import com.phynos.web.manager.json.ResultCodeEnum;
import com.phynos.web.manager.service.IUserService;

@Controller
public class LoginController {
		
	@Autowired
	private IUserService userService;
	
	@GetMapping
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String getLoginView(){
		return "login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult login(
			HttpServletRequest req,
			@RequestParam("name") String name,
			@RequestParam("password") String password
			){
		Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return JsonResult.code(ResultCodeEnum.OBJECT_UN_EXIST, req);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return JsonResult.code(ResultCodeEnum.USERNAME_PASSWORD_MISMATCH, req);
        } catch (Exception e) {
        	e.printStackTrace();
        	return JsonResult.code(ResultCodeEnum.SYSTEM_UNKNOWN_ERROR, req);
		}
        //if(subject.isAuthenticated())
		return JsonResult.code(ResultCodeEnum.OK);
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest req){
		HttpSession session= req.getSession();  
		session.invalidate();
		return "redirect:/login";
	}
	
	@RequestMapping(value="/captcha",method=RequestMethod.GET)
	@ResponseBody
	public void capture(
			HttpServletRequest req, 
			HttpServletResponse res) throws IOException{
		String code = CaptchaUtil.createCaptureImage(res.getOutputStream());
		System.out.println(code);
		res.getOutputStream().flush();
	}

}
